package com.itheima.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-09 11:12
 * @description
 */
public class DatasourceUtil {
    //这就是一个负责帮助我们往线程放置和获取放置对象的一个工具人!!
    private static ThreadLocal<Connection> connectionThreadLocal=new ThreadLocal<>();

    public static void setConnection(Connection connection){
        //放到线程中去了!!
        connectionThreadLocal.set(connection);
    }

    public static Connection getConnection(DataSource dataSource){
        //优先尝试从当前线程的获取连接
        Connection connection = connectionThreadLocal.get();
        if (connection==null){
            //意味着 没有管理事务
            try {
                connection=dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

}
